package com.wkbb.basic.controller.manage;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wkbb.basic.constant.BasicConstants;
import com.wkbb.basic.model.*;
import com.wkbb.basic.service.SysFunctionService;
import com.wkbb.basic.service.SysRoleService;
import com.wkbb.basic.service.SysRoleTemplateService;
import com.wkbb.basic.service.TeacherManageService;
import com.wkbb.basic.vo.*;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.Constants;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.EmployeeInfoDto;
import com.wkbb.common.dto.basic.RoleTypeJsonDto;
import com.wkbb.common.dto.basic.RoleUserDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.enums.SysFunctionTypeEnum;
import com.wkbb.common.enums.SysRoleTypeEnum;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author liuxiancan
 */
@RestController
@Api(description = "系统管理(后台管理)")
@RequestMapping("/basic/{apiVersion}/system/manage")
@Slf4j
public class SystemManageController extends BaseController {

    @Autowired
    private SysFunctionService sysFunctionService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysRoleTemplateService sysRoleTemplateService;

    @Autowired
    private TeacherManageService teacherManageService;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @ApiOperation(value = "查询菜单功能树形结构")
    @RequestMapping(value = "/getFunctionTreeList", method = RequestMethod.GET)
    public ResultDTO<List<SysFunctionVo>> getFunctionTreeList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion)
    {

        log.info("**********SystemManageController.getFunctionTreeList********apiVersion:{}", apiVersion);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {

            return new ResultDTO<List<SysFunctionVo>>(sysFunctionService.getFunctionTreeList(new HashMap<String, Object>()));

        } catch (Exception e) {
            log.error("**********SystemManageController.getFunctionTreeList********", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "新增菜单")
    @RequestMapping(value = "/addFunction", method = RequestMethod.POST)
    public ResultDTO<Long> addFunction(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "菜单详情", required = true) @RequestBody SysFunction sysFunction)
    {

        log.info("***********SystemManageController.add******apiVersion:{},sysFunction:{}", apiVersion, sysFunction);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if (sysFunction.getAppId() == null||sysFunction.getType() == null||StringUtil.isNullOrBlank(sysFunction.getName())) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            sysFunction.setCreateBy(userDto.getName());
            sysFunction.setUpdateBy(userDto.getName());
            sysFunctionService.insert(sysFunction);

            //全部清除菜单缓存
            this.clearUserMenuRedis(null);

            return new ResultDTO<>(sysFunction.getId());
        } catch (Exception e) {
            log.error("***********SystemManageController.add******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "修改菜单")
    @RequestMapping(value = "/updateFunction", method = RequestMethod.PUT)
    public ResultDTO<Long> updateFunction(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "菜单详情", required = true) @RequestBody SysFunction sysFunction)
    {

        log.info("***********SystemManageController.update******apiVersion:{},sysFunction:{}", apiVersion, sysFunction);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if (null==sysFunction.getId() || sysFunction.getAppId() == null||sysFunction.getType() == null||StringUtil.isNullOrBlank(sysFunction.getName())) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            sysFunction.setUpdateBy(userDto.getName());
            sysFunctionService.updateFunction(sysFunction);

            //全部清除菜单缓存
            this.clearUserMenuRedis(null);

            return new ResultDTO<>(sysFunction.getId());
        } catch (Exception e) {
            log.error("***********SystemManageController.update******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "删除菜单")
    @RequestMapping(value = "/deleteFunction", method = RequestMethod.DELETE)
    public ResultDTO<Long> deleteFunction(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "菜单ID", required = true) @RequestParam(name = "id", required = true) Long id)
    {

        log.info("***********SystemManageController.delete******apiVersion:{},id:{}", apiVersion, id);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if (id == null) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            SysFunction sysFunction = sysFunctionService.getByPrimaryKey(id);
            if(null!=sysFunction) {
                sysFunctionService.deleteByPrimaryKey(id);

                //全部清除菜单缓存
                this.clearUserMenuRedis(null);
            }

            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("***********SystemManageController.delete******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "查询角色列表")
    @RequestMapping(value = "/getRoleList", method = RequestMethod.GET)
    public ResultDTO<List<SysRole>> getRoleList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId)
    {

        log.info("**********SystemManageController.getRoleList********apiVersion:{},orgId:{}", apiVersion, orgId);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        //默认返回空列表
        if (null == orgId) {
            return new ResultDTO<>(new ArrayList<SysRole>());
        }

        try {
            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("orgId", orgId);

            return new ResultDTO<List<SysRole>>(sysRoleService.getListByMapParams(params));
        } catch (Exception e) {
            log.error("***********SystemManageController.getRoleList******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "查询角色分页列表")
    @RequestMapping(value = "/getRolePageList", method = RequestMethod.GET)
    public ResultDTO<PageInfo<SysRole>> getRolePageList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
//            @ApiParam(value = "组织ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "角色名称", required = false) @RequestParam(name = "roleName", required = false) String roleName,
            @ApiParam(value = "页码", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize)
    {
        log.info("**********SystemManageController.getRolePageList********apiVersion:{},pageNo:{},pageSize:{}", apiVersion, pageNo, pageSize);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

//        if (null == orgId) {
//            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
//        }

        try {
            HashMap<String, Object> params = new HashMap<String, Object>();
//            params.put("orgId", orgId);
            if (!StringUtils.isEmpty(roleName)) {
                params.put("roleName", roleName);
            }
            return new ResultDTO<PageInfo<SysRole>>(sysRoleService.getListByPage(params, pageNo, pageSize));
        } catch (Exception e) {
            log.error("查询角色分页列表", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "新增角色")
    @RequestMapping(value = "/addRole", method = RequestMethod.POST)
    public ResultDTO<SysRole> addRole(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "角色", required = true) @RequestBody SysRole sysRole)
    {

        log.info("***********SystemManageController.addRole******apiVersion:{},orgId:{},roleName:{}", apiVersion, sysRole.getOrgId(), sysRole.getRoleName());
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        Integer roleType = getRoleTypeByUser(userDto);

        try {
            if (null == sysRole.getOrgId() || StringUtil.isNullOrBlank(sysRole.getRoleName())) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            SysRole sysOrgRole = new SysRole();
            sysOrgRole.setApplicationId(BasicConstants.APPLICATION_ID);
            sysOrgRole.setOrgId(sysRole.getOrgId());
            sysOrgRole.setRoleName(sysRole.getRoleName());
            sysOrgRole.setStatus(true);
            if (SysRoleTypeEnum.SUPER_ADMIN.getValue() == roleType) {
                sysOrgRole.setRoleType((short) SysRoleTypeEnum.ADMIN.getValue());
            } else {
                sysOrgRole.setRoleType((short) SysRoleTypeEnum.EMPLOYEE.getValue());
            }

            sysOrgRole.setCreateBy(userDto.getName());
            sysOrgRole.setUpdateBy(userDto.getName());

            sysRoleService.insert(sysOrgRole);

            return new ResultDTO<SysRole>(sysOrgRole);
        } catch (Exception e) {
            log.error("***********SystemManageController.addRole******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "修改角色")
    @RequestMapping(value = "/updateRole", method = RequestMethod.PUT)
    public ResultDTO<Object> updateRole(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "角色", required = true) @RequestBody SysRole sysRole)
    {

        log.info("***********SystemManageController.updateRole******apiVersion:{},id:{},roleName:{}", apiVersion, sysRole.getOrgId(), sysRole.getRoleName());
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if (null == sysRole.getOrgId() || StringUtil.isNullOrBlank(sysRole.getRoleName())) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            SysRole sysOrgRole = new SysRole();
            sysOrgRole.setId(sysRole.getOrgId());
            sysOrgRole.setRoleName(sysRole.getRoleName());
            sysOrgRole.setUpdateBy(userDto.getName());

            sysRoleService.update(sysOrgRole);

            return new ResultDTO(true);

        } catch (Exception e) {
            log.error("***********SystemManageController.updateRole******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "删除角色")
    @RequestMapping(value = "/deleteRole", method = RequestMethod.DELETE)
    public ResultDTO<Object> deleteRole(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "角色ID", required = true) @RequestParam(name = "id", required = true) Long id)
    {

        log.info("***********SystemManageController.deleteRole******apiVersion:{},id:{}", apiVersion, id);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if (id == null) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            sysRoleService.deleteByPrimaryKey(id);

            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("***********SystemManageController.deleteRole******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "启用/禁用角色")
    @RequestMapping(value = "/updateRoleStatus", method = RequestMethod.POST)
    public ResultDTO<Object> updateRoleStatus(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "编号", required = true) @RequestParam(name = "roleId", required = true) Long id,
            @ApiParam(value = "状态(false禁用 true启用)", required = true) @RequestParam(name = "status", required = true) Boolean status)
    {

        log.info("***********SystemManageController.updateRoleStatus******apiVersion:{},id:{},status:{}", apiVersion, id, status);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {

            SysRole sysOrgRole = new SysRole();
            sysOrgRole.setId(id);
            sysOrgRole.setStatus(status);
            sysOrgRole.setUpdateBy(userDto.getName());

            sysRoleService.update(sysOrgRole);

            return new ResultDTO<Object>(true);

        } catch (Exception e) {
            log.error("***********SystemManageController.updateRoleStatus******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "查询角色下用户分页列表")
    @RequestMapping(value = "/getRoleUserPageList", method = RequestMethod.GET)
    public ResultDTO<PageInfo<SysRoleUserVo>> getRoleUserPageList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "角色ID", required = false) @RequestParam(name = "roleId", required = false) Long roleId,
            @ApiParam(value = "页码", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize)
    {

        log.info("**********SystemManageController.getRoleUserPageList********apiVersion:{},orgId:{},pageNo:{},pageSize:{}", apiVersion, orgId, pageNo, pageSize);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("orgId", orgId);
            params.put("roleId", roleId);

            return new ResultDTO<PageInfo<SysRoleUserVo>>(sysRoleService.getRoleUserPageList(params, pageNo, pageSize));
        } catch (Exception e) {
            log.error("**********SystemManageController.getRoleUserPageList********", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "查询待添加用户列表")
    @RequestMapping(value = "/getRoleUserList", method = RequestMethod.GET)
    public ResultDTO<List<RoleUserDto>> getRoleUserList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "角色ID", required = false) @RequestParam(name = "roleId", required = false) Long roleId)
    {

        log.info("**********SystemManageController.getRoleUserList********apiVersion:{},orgId:{}", apiVersion, orgId);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {

            List<RoleUserDto> roleUserDtoList = new ArrayList<RoleUserDto>();

            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("orgId", orgId);
            params.put("roleId", roleId);

            PageInfo<SysRoleUserVo> sysRoleUserPageList = sysRoleService.getRoleUserPageList(params, 1, 300);
            List<SysRoleUserVo> sysRoleUserList = sysRoleUserPageList.getList();

            Map<String, Object> employeeParams = new HashMap<>();
            employeeParams.put("orgId", orgId);
            List<EmployeeInfoDto> employeeInfoList = teacherManageService.getEmployeeInfoList(employeeParams);

            //重新组装数据
            for (EmployeeInfoDto employeeInfo : employeeInfoList)
            {
                RoleUserDto roleUserDto = new RoleUserDto();
                roleUserDto.setUserId(employeeInfo.getUserId());
                roleUserDto.setUserName(employeeInfo.getName());

                if(sysRoleUserList.size()>0) {
                    for(SysRoleUserVo sysRoleUserVo : sysRoleUserList) {
                        if(employeeInfo.getUserId().equals(sysRoleUserVo.getUserId())) {
                            roleUserDto.setStatus(true);
                            break;
                        }
                    }
                }
                roleUserDtoList.add(roleUserDto);
            }

            return new ResultDTO<List<RoleUserDto>>(roleUserDtoList);

        } catch (Exception e) {
            log.error("**********SystemManageController.getRoleUserPageList********", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "添加角色用户")
    @RequestMapping(value = "/addRoleUser", method = RequestMethod.POST)
    public ResultDTO<Object> addRoleUser(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "角色ID", required = true) @RequestParam(name = "roleId", required = true) Long roleId,
            @ApiParam(value = "用户ID集(以;分隔)", required = true) @RequestParam(name = "userIds", required = true) String userIds)
    {

        log.info("***********SystemManageController.addRoleUser******apiVersion:{},orgId:{},roleId:{},userIds:{}", apiVersion, orgId, roleId, userIds);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if (null == orgId || null == roleId) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            List<String> userIdList = new ArrayList<String>();
            if (!StringUtils.isEmpty(userIds)) {
                userIdList = Arrays.asList(userIds.split(Constants.SEPARATOR_MARK));
            }

            List<SysRoleUser> roleUserList = new ArrayList<SysRoleUser>();
            for (String userId : userIdList) {
                SysRoleUser sysRoleUser = new SysRoleUser();
                sysRoleUser.setOrgId(orgId);
                sysRoleUser.setRoleId(roleId);
                sysRoleUser.setUserId(Long.parseLong(userId));
                sysRoleUser.setCreateBy(userDto.getName());
                sysRoleUser.setUpdateBy(userDto.getName());

                roleUserList.add(sysRoleUser);
            }

            //批量保存
            sysRoleService.insertSysRoleUserBatch(orgId, roleId, roleUserList);

            //清除菜单缓存
            this.clearUserMenuRedis(orgId);

            return new ResultDTO<Object>(true);

        } catch (Exception e) {
            log.error("***********SystemManageController.addRoleUser******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "删除角色用户")
    @RequestMapping(value = "/deleteRoleUser", method = RequestMethod.DELETE)
    public ResultDTO<Object> deleteRoleUser(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "角色ID", required = true) @RequestParam(name = "roleId", required = true) Long roleId,
            @ApiParam(value = "用户ID集(以;分隔)", required = true) @RequestParam(name = "userIds", required = true) String userIds)
    {

        log.info("***********SystemManageController.deleteRoleUser******apiVersion:{},orgId:{},roleId:{},userIds:{}", apiVersion, orgId,roleId,userIds);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if (null == orgId || null == roleId || null==userIds) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            List<String> userIdList = new ArrayList<String>();
            if (!StringUtils.isEmpty(userIds)) {
                userIdList = Arrays.asList(userIds.split(Constants.SEPARATOR_MARK));
            }

            for (String userId : userIdList) {
                SysRoleUser sysRoleUser = new SysRoleUser();
                sysRoleUser.setOrgId(orgId);
                sysRoleUser.setRoleId(roleId);
                sysRoleUser.setUserId(Long.parseLong(userId));

                sysRoleService.deleteSysRoleUser(sysRoleUser);
            }

            //清除菜单缓存
            this.clearUserMenuRedis(orgId);

            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("***********SystemManageController.deleteRoleUser******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "查询角色下功能分页列表")
    @RequestMapping(value = "/getRoleFunctionPageList", method = RequestMethod.GET)
    public ResultDTO<PageInfo<SysRoleFunctionVo>> getRoleFunctionPageList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "角色ID", required = true) @RequestParam(name = "roleId", required = true) Long roleId,
            @ApiParam(value = "页码", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize)
    {

        log.info("**********SystemManageController.getRoleFunctionPageList********apiVersion:{},orgId:{},pageNo:{},pageSize:{}", apiVersion, orgId, pageNo, pageSize);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("orgId", orgId);
            params.put("roleId", roleId);

            return new ResultDTO<PageInfo<SysRoleFunctionVo>>(sysRoleService.getRoleFunctionPageList(params, pageNo, pageSize));
        } catch (Exception e) {
            log.error("**********SystemManageController.getRoleFunctionPageList********", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "查询角色下功能树形结构")
    @RequestMapping(value = "/getRoleFunctionTreeList", method = RequestMethod.GET)
    public ResultDTO<List<SysRoleFunctionVo>> getRoleFunctionTreeList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "角色ID", required = true) @RequestParam(name = "roleId", required = true) Long roleId)
    {

        log.info("**********SystemManageController.getRoleFunctionTreeList********apiVersion:{},orgId:{},roleId:{}", apiVersion, orgId,roleId);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            HashMap<String, Object> params = new HashMap<String, Object>();
//            params.put("orgId", orgId);
            params.put("roleId", roleId);

            return new ResultDTO<List<SysRoleFunctionVo>>(sysRoleService.getRoleFunctionTreeList(params));
        } catch (Exception e) {
            log.error("**********SystemManageController.getRoleFunctionTreeList********", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "保存角色的功能")
    @RequestMapping(value = "/saveSysRoleFunction", method = RequestMethod.POST)
    public ResultDTO<Object> saveSysRoleFunction(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "角色ID", required = true) @RequestParam(name = "roleId", required = true) Long roleId,
            @RequestBody List<SysRoleFunction> functionList)
    {

        log.info("***********SystemManageController.saveSysRoleFunction******apiVersion:{},orgId:{},roleId:{},functionList:{}", apiVersion, orgId, roleId, functionList);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if (null == orgId || null == roleId || functionList.size()==0) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            //批量保存
            if(functionList.size()>0) {
                for(SysRoleFunction roleFunction : functionList)
                {
                    roleFunction.setOrgId(orgId);
                    roleFunction.setRoleId(roleId);
                    roleFunction.setCreateBy(userDto.getName());
                    roleFunction.setUpdateBy(userDto.getName());
                }
                sysRoleService.saveSysRoleFunctionBatch(orgId,roleId,functionList);
            }

            //清除菜单缓存
            this.clearUserMenuRedis(orgId);

            return new ResultDTO<Object>(true);

        } catch (Exception e) {
            log.error("***********SystemManageController.saveSysRoleFunction******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "查询系统角色模板分页列表")
    @RequestMapping(value = "/getRoleTemplatePageList", method = RequestMethod.GET)
    public ResultDTO<PageInfo<SysRoleTemplate>> getRoleTemplatePageList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织类型（1微看 2代理商 3机关 4集团 5幼儿园 6小学 7中职 8初中 9高中 10高职 11本科 12培训学校）", required = true) @RequestParam(name = "orgType", required = true) Integer orgType,
            @ApiParam(value = "页码", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize)
    {

        log.info("**********SystemManageController.getRoleTemplatePageList********apiVersion:{},orgId:{},pageNo:{},pageSize:{}", apiVersion, orgType, pageNo, pageSize);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            HashMap<String, Object> params = new HashMap<String, Object>();
            if (null != orgType) {
                params.put("orgType", orgType);
            }
            return new ResultDTO<PageInfo<SysRoleTemplate>>(sysRoleTemplateService.getListByPage(params, pageNo, pageSize));
        } catch (Exception e) {
            log.error("***********SystemManageController.getRoleTemplatePageList******", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "新增系统角色模板")
    @RequestMapping(value = "/addRoleTemplate", method = RequestMethod.POST)
    public ResultDTO<SysRoleTemplate> addRoleTemplate(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "角色", required = true) @RequestBody SysRoleTemplate roleTemplate,
            @ApiParam(value = "是否管理员(0否 1是)", required = true) @RequestParam(name = "isAdmin", required = true) Boolean isAdmin)
    {

        log.info("***********SystemManageController.addRoleTemplate******apiVersion:{},orgType:{},roleName:{}", apiVersion, roleTemplate.getOrgType(), roleTemplate.getRoleName());
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if (null == roleTemplate.getOrgType() || StringUtil.isNullOrBlank(roleTemplate.getRoleName())) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            SysRoleTemplate sysRoleTemplate = new SysRoleTemplate();
            sysRoleTemplate.setApplicationId(BasicConstants.APPLICATION_ID);
            sysRoleTemplate.setOrgType(roleTemplate.getOrgType());
            sysRoleTemplate.setRoleName(roleTemplate.getRoleName());
            if(isAdmin) {
                sysRoleTemplate.setRoleType((short) SysRoleTypeEnum.ADMIN.getValue());
            }
            else
            {
                sysRoleTemplate.setRoleType((short) (short) SysRoleTypeEnum.EMPLOYEE.getValue());
            }
            sysRoleTemplate.setStatus(true);
            sysRoleTemplate.setCreateBy(userDto.getName());
            sysRoleTemplate.setUpdateBy(userDto.getName());

            sysRoleTemplateService.insert(sysRoleTemplate);

            return new ResultDTO<SysRoleTemplate>(sysRoleTemplate);
        } catch (Exception e) {
            log.error("***********SystemManageController.addRoleTemplate******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "修改系统角色模板")
    @RequestMapping(value = "/updateRoleTemplate", method = RequestMethod.PUT)
    public ResultDTO<Object> updateRoleTemplate(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "角色", required = true) @RequestBody SysRoleTemplate roleTemplate)
    {

        log.info("***********SystemManageController.updateRoleTemplate******apiVersion:{},id:{},roleName:{}", apiVersion, roleTemplate.getId(), roleTemplate.getRoleName());
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if (null == roleTemplate.getId() || StringUtil.isNullOrBlank(roleTemplate.getRoleName())) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            SysRoleTemplate sysRoleTemplate = new SysRoleTemplate();
            sysRoleTemplate.setId(roleTemplate.getId());
            sysRoleTemplate.setRoleName(roleTemplate.getRoleName());
            sysRoleTemplate.setUpdateBy(userDto.getName());

            sysRoleTemplateService.update(sysRoleTemplate);

            return new ResultDTO(true);

        } catch (Exception e) {
            log.error("***********SystemManageController.updateRoleTemplate******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "删除系统角色模板")
    @RequestMapping(value = "/deleteRoleTemplate", method = RequestMethod.DELETE)
    public ResultDTO<Object> deleteRoleTemplate(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "角色ID", required = true) @RequestParam(name = "id", required = true) Long id)
    {

        log.info("***********SystemManageController.deleteRoleTemplate******apiVersion:{},id:{}", apiVersion, id);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if (id == null) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            sysRoleTemplateService.deleteByPrimaryKey(id);

            return new ResultDTO<>(true);
        } catch (Exception e) {
            log.error("***********SystemManageController.deleteRoleTemplate******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "同步系统角色模板")
    @RequestMapping(value = "/syncRoleFunctionTemplate", method = RequestMethod.GET)
    public ResultDTO<Object> syncRoleFunctionTemplate(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId)
    {

        log.info("**********SystemManageController.syncRoleFunctionTemplate********apiVersion:{},orgId:{},orgId:{}", apiVersion, orgId);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        if (orgId == null) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {

            sysRoleService.syncRoleFunctionTemplate(orgId);

            return new ResultDTO<Object>(true);
        } catch (Exception e) {
            log.error("**********SystemManageController.syncRoleFunctionTemplate********", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "查询系统角色下功能树形结构")
    @RequestMapping(value = "/getRoleFunctionTemplateTreeList", method = RequestMethod.GET)
    public ResultDTO<List<SysRoleFunctionTemplateVo>> getRoleFunctionTemplateTreeList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "角色ID", required = true) @RequestParam(name = "roleId", required = true) Long roleId)
    {

        log.info("**********SystemManageController.getRoleFunctionTemplateTreeList********apiVersion:{},orgId:{},roleId:{}", apiVersion, roleId);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("templateRoleId", roleId);

            return new ResultDTO<List<SysRoleFunctionTemplateVo>>(sysRoleService.getRoleFunctionTemplateTreeList(params));
        } catch (Exception e) {
            log.error("**********SystemManageController.getRoleFunctionTemplateTreeList********", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "保存系统角色的功能")
    @RequestMapping(value = "/saveSysRoleFunctionTemplate", method = RequestMethod.POST)
    public ResultDTO<Object> saveSysRoleFunctionTemplate(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "角色ID", required = true) @RequestParam(name = "roleId", required = true) Long roleId,
            @RequestBody List<SysRoleFunctionTemplate> functionList)
    {

        log.info("***********SystemManageController.saveSysRoleFunctionTemplate******apiVersion:{},orgId:{},roleId:{},functionList:{}", apiVersion, roleId, functionList);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {
            if (null == roleId || functionList.size()==0) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            //批量保存
            if(functionList.size()>0) {
                for(SysRoleFunctionTemplate roleFunctionTemplate : functionList)
                {
                    roleFunctionTemplate.setTemplateRoleId(roleId);
                    roleFunctionTemplate.setCreateBy(userDto.getName());
                    roleFunctionTemplate.setUpdateBy(userDto.getName());
                }
                sysRoleService.saveSysRoleFunctionTemplateBatch(roleId,functionList);
            }

            return new ResultDTO<Object>(true);

        } catch (Exception e) {
            log.error("***********SystemManageController.saveSysRoleFunctionTemplate******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "查询用户权限分页列表")
    @RequestMapping(value = "/getUserRolePageList", method = RequestMethod.GET)
    public ResultDTO getUserRolePageList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "姓名",  required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(value = "手机号", required = false) @RequestParam(name = "mobile", required = false) String mobile,
            @ApiParam(value = "页码", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize)
    {

        log.info("**********SystemManageController.getUserRolePageList********apiVersion:{},orgId:{},pageNo:{},pageSize:{}", apiVersion, orgId, pageNo, pageSize);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        if (null == orgId) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {
            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("orgId", orgId);
            params.put("name", name);
            params.put("mobile", mobile);

            PageInfo<SysUserRoleVo> pageInfo = sysRoleService.getUserRolePageList(params, pageNo, pageSize);

            return new ResultDTO(pageInfo);
        } catch (Exception e) {
            log.error("**********SystemManageController.getUserRolePageList********", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "查询当前用户全部功能树形结构")
    @RequestMapping(value = "/getUserAllFunctionTreeList", method = RequestMethod.GET)
    public ResultDTO<List<SysRoleFunctionVo>> getUserAllFunctionTreeList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion)
    {

        log.info("**********SystemManageController.getUserAllFunctionTreeList********apiVersion:{}", apiVersion);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        try {

            List<SysFunctionVo> sysFunctionList = null;
            Long orgId = super.getOrgByUser(userDto).getId();
            Integer roleType = getRoleTypeByUser(userDto);

            log.info("**********SystemManageController.getUserAllFunctionTreeList********roleType:{}", roleType);

            //先从缓存中获取
            String menuRedisKey = RedisKeyConstant.MENU + "org_" + orgId + "_user_" + userDto.getId();
            String menuJsonStr = redisTemplateUtil.getJSON(menuRedisKey);
            if(StringUtil.isNotEmpty(menuJsonStr))
            {
                List<SysRoleFunctionVo> sysRoleFunctionList = JSONArray.parseObject(menuJsonStr,List.class);
                if(!sysRoleFunctionList.isEmpty())
                {
                    return new ResultDTO<List<SysRoleFunctionVo>>(sysRoleFunctionList);
                }
            }

            if (SysRoleTypeEnum.SUPER_ADMIN.getValue() == roleType) {
                log.info("**********SystemManageController.getUserAllFunctionTreeList****SUPER_ADMIN****");
                sysFunctionList = sysFunctionService.getFunctionTreeList(new HashMap<String, Object>());
            }
            else
            {
                //根据当前用户查询菜单
                HashMap<String, Object> params = new HashMap<String, Object>();
                params.put("orgId", orgId);
                params.put("userId", userDto.getId());
                params.put("parentId", 0);

                log.info("**********SystemManageController.getUserAllFunctionTreeList****params:{}****",params.toString());

                sysFunctionList = sysRoleService.getUserFunctionTreeList(params);
            }

            List<SysRoleFunctionVo> sysRoleFunctionList = this.copyUserFunctionList(orgId,sysFunctionList);
            //放入缓存中
            if(!sysRoleFunctionList.isEmpty())
            {
                redisTemplateUtil.set(menuRedisKey,sysRoleFunctionList);
            }

            return new ResultDTO<List<SysRoleFunctionVo>>(sysRoleFunctionList);

        } catch (Exception e) {
            log.error("**********SystemManageController.getUserAllFunctionTreeList********", e);
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "根据组织及用户查询所分配的功能树形结构")
    @RequestMapping(value = "/getUserFunctionTreeList", method = RequestMethod.GET)
    public ResultDTO<List<SysRoleFunctionVo>> getUserFunctionTreeList(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId)
    {

        log.info("**********SystemManageController.getFunctionTreeList********apiVersion:{}", apiVersion);
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }

        if (null == orgId) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {

                //根据当前用户查询菜单
                HashMap<String, Object> params = new HashMap<String, Object>();
                params.put("orgId", orgId);
                params.put("userId", userId);
                params.put("parentId", 0);

                List<SysFunctionVo> sysFunctionList = sysRoleService.getUserFunctionTreeList(params);

                List<SysRoleFunctionVo> sysRoleFunctionList = this.copyUserFunctionList(orgId,sysFunctionList);

            return new ResultDTO<List<SysRoleFunctionVo>>(sysRoleFunctionList);

        } catch (Exception e) {
            log.error("**********SystemManageController.getRoleFunctionTreeList********", e);
            return new ResultDTO<>(false);
        }
    }

    //递归复制菜单
    private List<SysRoleFunctionVo> copyUserFunctionList(Long orgId, List<SysFunctionVo> sysFunctionList)
    {
        //重新组装菜单
        List<SysRoleFunctionVo> sysRoleFunctionList = new ArrayList<SysRoleFunctionVo>();
        for(SysFunctionVo sysFunction : sysFunctionList)
        {

            com.wkbb.basic.vo.SysRoleFunctionVo sysRoleFunctionVo = new com.wkbb.basic.vo.SysRoleFunctionVo();
            sysRoleFunctionVo.setOrgId(orgId);
            sysRoleFunctionVo.setFunctionId(sysFunction.getId());
            sysRoleFunctionVo.setFunctionName(sysFunction.getName());
            sysRoleFunctionVo.setParentFunctionId(sysFunction.getParentId());
            sysRoleFunctionVo.setUrl(sysFunction.getUrl());

            //递归查询子菜单
            recursiveSysRoleFunction(orgId, sysFunction, sysRoleFunctionVo);

            sysRoleFunctionList.add(sysRoleFunctionVo);
        }

        return sysRoleFunctionList;
    }

    /**
     * 递归查询子菜单
     * */
    private void recursiveSysRoleFunction(Long orgId, SysFunctionVo sysFunction,SysRoleFunctionVo sysRoleFunctionVo)
    {
        List<SysRoleFunctionVo> sysRoleFunctionChildList = new ArrayList<SysRoleFunctionVo>();
        for(SysFunctionVo sysFunctionChild : sysFunction.getChildren()) {

            SysRoleFunctionVo sysRoleFunctionChildVo = new SysRoleFunctionVo();
            sysRoleFunctionChildVo.setOrgId(orgId);
            sysRoleFunctionChildVo.setFunctionId(sysFunctionChild.getId());
            sysRoleFunctionChildVo.setFunctionName(sysFunctionChild.getName());
            sysRoleFunctionChildVo.setParentFunctionId(sysFunctionChild.getParentId());
            sysRoleFunctionChildVo.setUrl(sysFunctionChild.getUrl());

            if(sysFunctionChild.getChildren().size()>0)
            {
                this.recursiveSysRoleFunction(orgId, sysFunctionChild, sysRoleFunctionChildVo);
            }

            sysRoleFunctionChildList.add(sysRoleFunctionChildVo);
        }

        sysRoleFunctionVo.setChildren(sysRoleFunctionChildList);

    }

    //清除菜单缓存
    private void clearUserMenuRedis(Long orgId)
    {
        String menuRedisKey = RedisKeyConstant.MENU;

        //清除菜单缓存
        if(null==orgId)
        {
            menuRedisKey = menuRedisKey + "org_*";
        }
        else
        {
            menuRedisKey = RedisKeyConstant.MENU + "org_" + orgId+"_user_*";
        }

        log.info("******clearUserMenuRedis******orgId:{},menuRedisKey:{}",orgId, menuRedisKey);

        redisTemplateUtil.delKeysLike(menuRedisKey);
    }
}
